package com.amado.course35Concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 一个可重入的互斥锁 Lock， 它具有与使用 synchronized 方法和语句所访问的隐式监视器锁相同的一些基本行为和语义，但功能更强大。
 * ReentrantLock必须要手工加锁、释放锁，synchronized是自动加锁、释放锁
 * <p>
 * ReentrantReadWriteLock 读写锁，如果有线程写才锁住程序 Created by Administrator on 2018/7/30.
 */
public class S08ReentrantLockTest {
	private static final ReentrantLock lock = new ReentrantLock();
	private static long count;

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					addByLock();
				}
			});
		}

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("count" + count);
	}

	public static void add() {
		try {
//            lock.lock();
			count++;
		} finally {
//            lock.unlock();
		}
	}

	public static void addByLock() {
		try {
			// 获取锁
			System.out.println("准备得到锁");
			lock.lock();
			// 尝试获取锁，如果没有被其它线程锁定获取锁返回true,否则返回false
//            lock.tryLock();
			Thread.sleep(1000);
			System.out.println("正在等待获取锁的线程数" + lock.getQueueLength());
			count++;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			// 解锁
			lock.unlock();
			System.out.println("释放锁");
		}
	}

	public static void addSynchronized() {
		synchronized (lock) {
			count++;
		}
	}
}
